package com.gxar.quick.ar.server.base.facade;

import com.alibaba.fastjson.JSONObject;
import com.gxar.common.entity.login.UserProfile;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.common.enums.DeletedEnum;
import com.gxar.quick.ar.server.base.common.enums.ExchangeMethodEnum;
import com.gxar.quick.ar.server.base.common.properties.QiMenProperties;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.exchange.mapper.ExchangeItemMapstruct;
import com.gxar.quick.ar.server.base.model.exchange.vo.response.ExchangeItemLotteryResponse;
import com.gxar.quick.ar.server.base.model.exchange.vo.response.ExchangeItemWriteOffResponse;
import com.gxar.quick.ar.server.base.model.user.exchange.vo.response.UserExchangeItemWorksResponse;
import com.gxar.quick.ar.server.base.model.user.vo.ExchangeCodeVO;
import com.gxar.quick.ar.server.base.reference.QimenReference;
import com.gxar.quick.ar.server.base.sdk.QiMenSDK;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemMapper;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemUserMapper;
import com.gxar.quick.ar.server.db.mapper.ExchangeItemWorksMapper;
import com.gxar.quick.ar.server.db.model.ExchangeItemEntity;
import com.gxar.quick.ar.server.db.model.ExchangeItemUserEntity;
import com.gxar.quick.ar.server.db.model.ExchangeItemWorksEntity;
import com.gxar.quick.ar.server.db.model.WorksEntity;
import com.gxar.quick.ar.server.db.repository.ExchangeItemUserRepository;
import com.gxar.quick.ar.server.db.repository.WorksRepository;
import com.gxar.quick.ar.server.db.service.ExchangeItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/4/11 15:17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExchangeItemFacade {

    private final QiMenProperties qiMenProperties;

    private final ExchangeItemService exchangeItemService;

    private final ExchangeItemMapper exchangeItemMapper;
    private final ExchangeItemWorksMapper exchangeItemWorksMapper;
    private final ExchangeItemUserMapper exchangeItemUserMapper;

    private final WorksRepository worksRepository;


    /**
     * 兑换品兑换
     *
     * @param userProfile 用户信息
     * @param code        兑换码
     */
    @Transactional(rollbackFor = Throwable.class)
    public void exchange(UserProfile userProfile, String code) {
        ExchangeItemEntity exchangeCodeEntity = exchangeItemMapper.findByCode(code);
        if (Objects.isNull(exchangeCodeEntity)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_CODE_INVALID);
        }
        List<ExchangeItemUserEntity> exchangeItemUserEntityList = exchangeItemUserMapper.queryUserExchanged(code, userProfile.getId(), false);
        if (CollectionUtils.isEmpty(exchangeItemUserEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_CODE_INVALID);
        }

        List<ExchangeItemWorksEntity> exchangeItemWorksEntityList = exchangeItemWorksMapper.findByCode(exchangeCodeEntity.getCode());
        if (CollectionUtils.isEmpty(exchangeItemWorksEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_WORKS_IS_NULL);
        }
        List<Long> worksIdList = exchangeItemWorksEntityList.stream().map(ExchangeItemWorksEntity::getWorksId).collect(Collectors.toList());
        List<WorksEntity> worksEntities = worksRepository.findAllById(worksIdList);
        List<WorksEntity> worksEntityList = worksEntities.stream().filter(WorksEntity::getShelves).filter(e -> DeletedEnum.FALSE.getCode().equals(e.getDeleted())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(worksEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_WORKS_IS_NULL);
        }

        Date date = new Date();
        for (ExchangeItemUserEntity exchangeItemUserEntity : exchangeItemUserEntityList) {
            exchangeItemService.exchange(userProfile, date, exchangeCodeEntity, exchangeItemUserEntity, worksEntityList);
        }
    }


    /**
     * 用户兑换品作品详情
     *
     * @param userId   用户ID
     * @param itemCode 兑换码
     * @return 响应
     */
    public UserExchangeItemWorksResponse userExchangeItemWorks(Long userId, String itemCode) {
        ExchangeItemEntity exchangeItemEntity = exchangeItemMapper.findByCode(itemCode);
        if (Objects.isNull(exchangeItemEntity)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_CODE_INVALID);
        }
        if (!exchangeItemEntity.getActivityEnable()) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_ACTIVITY_DISABLE);
        }
        List<ExchangeItemWorksEntity> worksEntities = exchangeItemWorksMapper.findByCode(itemCode);
        if (CollectionUtils.isEmpty(worksEntities)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_WORKS_IS_NULL);
        }
        UserExchangeItemWorksResponse response = ExchangeItemMapstruct.INSTANCE.entityToWorks(exchangeItemEntity);
        ExchangeItemWorksEntity exchangeItemWorksEntity = worksEntities.get(0);
        Optional<WorksEntity> worksEntityOptional = worksRepository.findById(exchangeItemWorksEntity.getWorksId());
        if (worksEntityOptional.isPresent()) {
            WorksEntity worksEntity = worksEntityOptional.get();
            response.setWorkId(String.valueOf(worksEntity.getId()));
            response.setIdentify(worksEntity.getIdentify());
            response.setContent(worksEntity.getContent());
        }
        if (response.getActivityEnable()) {
            // 校验是否领取
            List<ExchangeItemUserEntity> exchangeItemUserEntityList = exchangeItemUserMapper.queryUserExchangedAndMethod(itemCode, userId, false, ExchangeMethodEnum.SCAN.getCode());
            if (CollectionUtils.isNotEmpty(exchangeItemUserEntityList)) {
                ExchangeItemUserEntity exchangeItemUserEntity = exchangeItemUserEntityList.get(0);
                response.setActivityEnable(exchangeItemUserEntity.getActivityEnable());
                response.setUserExchangeItemId(exchangeItemUserEntity.getId().toString());
            }
        }
        return response;
    }

    /**
     * 抽奖
     *
     * @param userProfile 用户
     * @param code        兑换码
     * @return 是否成功
     */
    @Transactional(rollbackFor = Throwable.class)
    public ExchangeItemLotteryResponse lottery(UserProfile userProfile, String code, String qimenToken) {
        List<ExchangeItemEntity> itemInCodeList = exchangeItemService.findItemInCodeList(Collections.singletonList(code));
        if (CollectionUtils.isEmpty(itemInCodeList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_CODE_INVALID);
        }
        ExchangeItemEntity exchangeItemEntity = itemInCodeList.get(0);
        if (!exchangeItemEntity.getActivityEnable()) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_ACTIVITY_DISABLE);
        }
        List<ExchangeItemUserEntity> exchangeItemUserEntityList = exchangeItemUserMapper.queryUserExchangedAndMethod(code, userProfile.getId(), false, ExchangeMethodEnum.SCAN.getCode());
        if (CollectionUtils.isNotEmpty(exchangeItemUserEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_RECEIVED);
        }
        // 1、发放作品
        List<ExchangeCodeVO> exchangeCodeList = new ArrayList<>();
        ExchangeCodeVO codeVo = new ExchangeCodeVO();
        codeVo.setCode(code);
        codeVo.setNum(1);
        exchangeCodeList.add(codeVo);
        List<String> saveCodes = exchangeItemService.saveExchangeItemUser(userProfile, userProfile.getId(), userProfile.getMobile(), exchangeCodeList, itemInCodeList);
        exchangeItemService.saveExchangeItemRecord(userProfile, userProfile.getId(), exchangeCodeList);
        ExchangeItemLotteryResponse response = new ExchangeItemLotteryResponse();
        response.setCode(saveCodes.get(0));
        if (StringUtils.isNotBlank(exchangeItemEntity.getActivityId())) {
            // 2、奇门抽奖
            String url = qiMenProperties.getUrl();
            JSONObject lotteryRes = QiMenSDK.lottery(url, qimenToken, exchangeItemEntity.getActivityId());
            String redeemCode = lotteryRes.getString("redeemCode");
            String giftName = lotteryRes.getString("prizeName");
            String giftType = lotteryRes.getString("prizeSubtitle");
            Integer prizeHisId = lotteryRes.getInteger("prizeHisId");
            String id = saveCodes.get(0);
            ExchangeItemUserEntity exchangeItemUserEntity = exchangeItemService.findUserItemById(Long.parseLong(id));
            if (Objects.nonNull(exchangeItemUserEntity)) {
                exchangeItemUserEntity.setPrizeHisId(String.valueOf(prizeHisId));
                exchangeItemService.saveExchangeItemUser(exchangeItemUserEntity);
            }
            response.setRedeemCode(redeemCode);
            response.setGiftName(giftName);
            response.setGiftType(giftType);
            response.setPrizeHisId(prizeHisId);
        }
        return response;
    }

    /**
     * 核销
     *
     * @param userProfile 用户信息
     * @param code        兑换码
     * @param token       奇门token
     * @return 响应
     */
    @Transactional(rollbackFor = Throwable.class)
    public ExchangeItemWriteOffResponse writeOff(UserProfile userProfile, String code, String token) {
        // 1、兑换作品
        ExchangeItemEntity exchangeItemEntity = exchangeItemService.findItemByCode(code);
        List<ExchangeItemUserEntity> exchangeItemUserEntityList = exchangeItemUserMapper.queryUserExchangedAndMethod(code, userProfile.getId(), false, ExchangeMethodEnum.SCAN.getCode());
        if (CollectionUtils.isNotEmpty(exchangeItemUserEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_CODE_WRITTEN_OFF);
        }
        List<ExchangeItemWorksEntity> exchangeItemWorks = exchangeItemWorksMapper.findByCode(code);
        if (CollectionUtils.isEmpty(exchangeItemWorks)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_WRITTEN_OFF_IS_NULL);
        }
        List<Long> worksIdList = exchangeItemWorks.stream().map(ExchangeItemWorksEntity::getWorksId).collect(Collectors.toList());
        List<WorksEntity> worksEntities = worksRepository.findAllById(worksIdList);
        List<WorksEntity> worksEntityList = worksEntities.stream().filter(WorksEntity::getShelves).filter(e -> DeletedEnum.FALSE.getCode().equals(e.getDeleted())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(worksEntityList)) {
            throw new APIRuntimeException(ResultCodeEnum.EXCHANGE_WORKS_IS_NULL);
        }
        Date date = new Date();
        ExchangeItemUserEntity exchangeItemUserEntity = exchangeItemUserEntityList.get(0);
        exchangeItemUserEntity.setActivityEnable(false);
        exchangeItemService.exchange(userProfile, date, exchangeItemEntity, exchangeItemUserEntity, worksEntityList);
        ExchangeItemWriteOffResponse response = new ExchangeItemWriteOffResponse();
        if (StringUtils.isNotBlank(exchangeItemUserEntity.getPrizeHisId())) {
            // TODO 奇门核销
            String url = qiMenProperties.getUrl();
            JSONObject lotteryRes = QiMenSDK.writeOff(url, token, exchangeItemUserEntity.getPrizeHisId());
        }
        return response;
    }
}
